from typing import Any, Dict, List, Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus

from modules.system.models.dept import Department
from modules.system.schemas.dept_schemas import DeptCreate, DeptUpdate
from modules.system.params.dept_params import DeptQuery

class DeptRepository(CRUDPlus[Department]):
    """部门仓储类"""

    async def get_by_id(self, db: AsyncSession, pk: int) -> Optional[Department]:
        """
        根据ID获取部门
        :param db: 数据库会话
        :param pk: 部门ID
        :return: 部门对象（如果存在）
        """
        return await self.select_model_by_column(db, id=pk, status=1)

    async def get_by_code(self, db: AsyncSession, dept_code: str) -> Optional[Department]:
        """
        根据部门编码获取部门
        :param db: 数据库会话
        :param dept_code: 部门编码
        :return: 部门对象（如果存在）
        """
        return await self.select_model_by_column(db, dept_code=dept_code, status=1)
        

    async def get_by_name(self, db: AsyncSession, dept_name: str) -> Optional[Department]:
        """
        根据部门名称获取部门
        :param db: 数据库会话
        :param dept_name: 部门名称
        :return: 部门对象（如果存在）
        """
        return await self.select_model_by_column(db, dept_name=dept_name, status=1)


    async def create(self, db: AsyncSession, data: DeptCreate) -> Department:
        """
        创建部门
        :param db: 数据库会话
        :param data: 创建数据
        :return: 创建后的部门对象
        """
        return await self.create_model(db, data)

    async def update(self, db: AsyncSession, pk: int, data: DeptUpdate) -> Optional[Department]:
        """
        更新部门信息
        :param db: 数据库会话
        :param pk: 部门ID
        :param data: 更新数据
        :return: 更新后的部门对象
        """
        await self.update_model(db, pk, data)
        return await self.select_model(db, pk)

    async def delete(self, db: AsyncSession, pk: int) -> bool:
        """
        删除部门
        :param db: 数据库会话
        :param pk: 部门ID
        :return: 删除成功与否
        """
        return await self.delete_model(db, pk)

    async def select_by_query(self, db: AsyncSession, query_params: DeptQuery) -> list[Department]:
        """执行查询并返回 ORM 行列表，适用于树构建等场景。"""
        from utils.query_builder import build_select_stmt
        stmt = build_select_stmt(Department, query_params)
        stmt = stmt.order_by(Department.dept_code.asc())
        res = await db.execute(stmt)
        return res.scalars().all()

    async def get_children(self, db: AsyncSession, dept_id: int) -> List[Department]:
        """获取指定部门的所有子部门（递归）"""
        return await self.select_models(db, parent_id=dept_id, del_flag=0)

dept_dao = DeptRepository(Department)